package cn.edu.seu.herald.informationplatform.filter;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.Activity;
import cn.edu.seu.herald.informationplatform.dao.database.ActivityDao;

public class ActivityRequired implements Filter {
	
	public static final String PARAM_NAME_OF_ACTIVITY_ID = "activity";

	public static final String ACTIVITY_BEAN_NAME = "activityBean";

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request,
			ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		boolean success = doSpecified(httpRequest, httpResponse);
		if (!success) {
			httpResponse.sendError(404);
			return;
		}
		
		int activityId = getActivityId(httpRequest);
		
		try {
			ActivityDao access = ActivityDao.getDao();
			Activity activity = access.getActivityById(activityId);
			request.setAttribute(ACTIVITY_BEAN_NAME, activity);
		} catch (SQLException e) {
			httpResponse.sendError(404);
			return;
		}
		
		chain.doFilter(request, response);
	}
	
	private boolean doSpecified(HttpServletRequest httpRequest,
			HttpServletResponse httpResponse) throws IOException {
		try {
			// 获取请求中的活动标识
			String activityIdParam = httpRequest.getParameter(
					PARAM_NAME_OF_ACTIVITY_ID);
			String leagueIdParam = httpRequest.getParameter(
					LeagueSpecified.PARAM_NAME_OF_LEAGUE_ID);
			int leagueId = Integer.valueOf(leagueIdParam);
			if (activityIdParam == null) {
			}
			ActivityDao access = ActivityDao.getDao();
			int activityId = Integer.valueOf(activityIdParam);
			if (!access.hasId(activityId)) {
				return false;
			}
			Activity activity = access.getActivityById(activityId);
			if (activity.getLeagueId() != leagueId) {
				return false;
			}
		} catch (SQLException e) {
			return false;
		} catch (NumberFormatException e) {
			return false;
		}
		
		return true;
	}
	
	private int getActivityId(HttpServletRequest httpRequest) {
		String activityIdParam = httpRequest.getParameter(
				PARAM_NAME_OF_ACTIVITY_ID);
		return Integer.parseInt(activityIdParam);
	}

}
